package com.seventh.tickets.service.Impl;

import com.seventh.tickets.entity.User;
import com.seventh.tickets.entity.Userdetail;
import com.seventh.tickets.repository.UserRepository;
import com.seventh.tickets.repository.UserdetailRepository;
import com.seventh.tickets.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    private  final UserRepository userRepository;
    private final UserdetailRepository userdetailRepository;
    public  UserServiceImpl(UserRepository userRepository,UserdetailRepository userdetailRepository){
        this.userRepository = userRepository;
        this.userdetailRepository = userdetailRepository;
    }
    @Override
    public String userLogin (String userloginname,String password)  {
        User user = userRepository.findByUserloginname(userloginname);
        if(user == null){
            return "1";
        }else {
            if (user.getUserpassword().equals(password)){
                return  "0";
            }else {
                return "2";
            }
        }
    }

    @Override
    public User userRegister(String userloginname, String password) throws Exception {
        User user2 = userRepository.findByUserloginname(userloginname);
        if (user2!=null){
           User xuser = new User();
           xuser.setUserloginname("已存在");
            return xuser;
        }else {
            User user = new User();
            user.setUserloginname(userloginname);
            user.setUserpassword(password);
            user.setUsertype(1);
            user = userRepository.save(user);
            System.out.println(user);
            if (user.getUserid()>0){
                Userdetail userdetail = new Userdetail();
                userdetail.setUserloginname(userloginname);
                userdetail = userdetailRepository.save(userdetail);
                if (userdetail.getDetailid()<=0){
                    throw new Exception("用户详细信息增加失败，用户注册失败");
                }else {
                    return  user;
                }
            }else {
                throw new Exception("用户注册失败!");
            }
        }

    }
}
